<?php
namespace app\index\controller;
use app\common\controller\CommonController;
use think\Db;
class ApiController extends CommonController
{
    /************************************************* 前台抽奖相关 **********************************************/
    /**
     * 获取活动时间
     */
    public function info()
    {
        try {
            if($this->request->isPost()){
                $date = Db::table('active_config')->field('date_start,date_end')->find();
                echo json_encode(['code' => 1000,'msg' => 'success','data' => $date]);exit;    
            }    
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }
    }

    /**
     * 抽奖接口
     * @param string $uuid  用户唯一id
     * @param string $type  抽奖的类型  每日免费的:free 观看广告视频的:ad 转发朋友圈的:friend
     */
    public function draw()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                if(empty($data['uuid'])){
                    echo json_encode(['code' => 2001,'msg' => 'fail','sub_msg' => 'invalid uuid']);exit;
                }
                if(empty($data['type']) || !in_array($data['type'],['free','ad','friend'])){
                    echo json_encode(['code' => 2001,'msg' => 'fail','sub_msg' => 'invalid type']);exit;
                }
                $type = $data['type'];
                $uuid = $data['uuid'];
                //用户存在判断
                $uuidinfo = Db::table('user')->where(['uuid' => $uuid])->find();
                if(!$uuidinfo){
                    Db::table('user')->insert(['uuid' => $uuid]);    
                }
                //活动时间判断
                $date = Db::table('active_config')->field('date_start,date_end')->find();
                if(empty($date['date_start']) || empty($date['date_end'])){
                    //获取活动时间失败
                    echo json_encode(['code' => 2008,'msg' => 'fail','sub_msg' => 'get the active date fail']);exit;    
                }
                //活动未开始
                if(date('Y-m-d') < $date['date_start']){ 
                    echo json_encode(['code' => 2009,'msg' => 'fail','sub_msg' => 'activity not started']);exit;
                }
                //活动已结束
                if(date('Y-m-d') > $date['date_end']){
                    echo json_encode(['code' => 2011,'msg' => 'fail','sub_msg' => 'activity has ended']);exit;    
                }
                //当日抽奖次数判断和三次抽奖类型判断
                $day = date('Y-m-d');
                $has_drawed = Db::table('draw')->where("uuid = '{$uuid}' AND DATE_FORMAT(`draw_date`,'%Y-%m-%d') = '{$day}'")->select();
                if(count($has_drawed) >= 3){
                    //当日三次机会用完
                    echo json_encode(['code' => 2002,'msg' => 'fail','sub_msg' => 'the number of draws has been used up']);exit;    
                }
                
                foreach ($has_drawed as $key => $value) {
                    if($type == 'free'){
                        if($value['type'] == 'free'){
                            //当日一次免费机会用完
                            echo json_encode(['code' => 2003,'msg' => 'fail','sub_msg' => 'the number of free has been used up']);exit;    
                        }
                    }
                    if($type == 'ad'){
                        if($value['type'] == 'ad'){
                            //当日一次观看广告机会用完
                            echo json_encode(['code' => 2004,'msg' => 'fail','sub_msg' => 'the number of ad has been used up']);exit;    
                        }
                    }
                    if($type == 'friend'){
                        if($value['type'] == 'friend'){
                            //当日一次分享朋友圈机会用完
                            echo json_encode(['code' => 2005,'msg' => 'fail','sub_msg' => 'the number of friend has been used up']);exit;    
                        }
                    }
                }
                $prizes = Db::table('prize')->order('rate asc')->select();
                if(!$prizes){
                    //获取奖品信息失败
                    echo json_encode(['code' => 2006,'msg' => 'fail','sub_msg' => 'get the prize info fail']);exit;    
                }
                $prize_draw = [];
                foreach ($prizes as $key => $value) {
                    $prize_draw[$value['name']]['id'] = $value['id'];       
                    $prize_draw[$value['name']]['residuenum'] = $value['residuenum'];       
                    $prize_draw[$value['name']]['num'] = $value['num'];       
                    $prize_draw[$value['name']]['rate'] = $value['rate'] * 100;       
                }
                
                $draw_result = $this->drawLottery($prize_draw);
                if(!$draw_result){
                    //抽奖失败
                    echo json_encode(['code' => 2007,'msg' => 'fail','sub_msg' => 'draw fail,please try again']);exit;    
                }
                
                //奖品分析
                $prize_info = [];//存放奖品信息

                //如果是爱奇艺兑换码,处理相关逻辑
                if($draw_result['winningPrizeId'] == 2){
                    $aiqiyi_code = Db::query("SELECT * FROM aiqiyi_code WHERE isused = 1 LIMIT 1 for UPDATE");
                    $aiqiyi_code = isset($aiqiyi_code[0]) ? $aiqiyi_code[0] : [];
                    if(!$aiqiyi_code){
                        //没有可用的兑换码,直接返回六必居奖品,winningPrizeId = 7
                        $prize_info['prize_id'] = 7;
                        $drawid = Db::table('draw')->insertGetId([
                            'type'      => $type,
                            'uuid'      => $uuid,
                            'draw_date' => date('Y-m-d H:i:s'),
                            'prize_id'  => 7,
                            'draw_info' => '',
                        ]);
                        $prize_info['draw_id'] = $drawid; 
                        echo json_encode(['code' => 1000,'msg' => 'success','data' => $prize_info]);exit;
                    }else{
                        Db::query("UPDATE aiqiyi_code SET isused = 2 WHERE id = {$aiqiyi_code['id']}");
                        $drawid = Db::table('draw')->insertGetId([
                            'type'      => $type,
                            'uuid'      => $uuid,
                            'draw_date' => date('Y-m-d H:i:s'),
                            'prize_id'  => $draw_result['winningPrizeId'],
                            'draw_info' => $aiqiyi_code['code'],
                        ]);
                        $prize_info['prize_id'] = $draw_result['winningPrizeId'];
                        $prize_info['draw_id']  = $drawid; 
                        $prize_info['code']     = $aiqiyi_code['code']; 
                        echo json_encode(['code' => 1000,'msg' => 'success','data' => $prize_info]);exit;
                    }   
                }
                //抽奖记录记录
                $drawid = Db::table('draw')->insertGetId([
                    'type'      => $type,
                    'uuid'      => $uuid,
                    'draw_date' => date('Y-m-d H:i:s'),
                    'prize_id'  => $draw_result['winningPrizeId'],
                    'draw_info' => '',
                ]);
                $prize_info['prize_id'] = $draw_result['winningPrizeId'];
                $prize_info['draw_id']  = $drawid;
                echo json_encode(['code' => 1000,'msg' => 'success','data' => $prize_info]);exit;
            }    
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }
    }

    /**
     * 提交地址信息接口
     * @param int       $draw_id
     * @param string    $name
     * @param string    $address
     * @param string    $phone
     */
    public function add()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                if(empty($data['draw_id']) || empty($data['name']) || empty($data['address']) || empty($data['phone'])){
                    echo json_encode(['code' => 2001,'msg' => 'fail','sub_msg' => 'invalid params,please check']);exit;    
                }
                $draw_info = '姓名：'. trim($data['name']) . '，电话：' . trim($data['phone']) . '，地址：' . trim($data['address']);
                $res = Db::table('draw')->where(['id' => $data['draw_id']])->update([
                    'draw_info' => $draw_info
                ]);
                if($res){
                    echo json_encode(['code' => 1000,'msg' => 'success','data' => []]);exit;    
                }
                echo json_encode(['code' => 2010,'msg' => 'fail','sub_msg' => 'submit fail,try again']);exit;
            }    
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }
    }

    // 抽奖函数
    protected function drawLottery($prizes) 
    {
        try {
            //开启事务
            Db::startTrans();

            $randomNumber = mt_rand() / mt_getrandmax();
            $winningPrize = null;
            
            $totalProbability = 0;
            foreach ($prizes as $prize => $info) {
                if ($info['residuenum'] > 0) {
                    $totalProbability += $info['rate'];
                }
            }
            
            $accumulatedProbability = 0;
            foreach ($prizes as $prize => $info) {
                if ($info['residuenum'] > 0) {
                    $probability = $info['rate'] / $totalProbability;
                    $accumulatedProbability += $probability;
            
                    if ($randomNumber <= $accumulatedProbability) {
                        $winningPrize = $prize;
                        $winningPrizeId = $prizes[$prize]['id'];
                        if ($info['residuenum'] !== 0) {
                            //减少奖品个数
                            //开启行锁更新数量
                            $prize_res = Db::query("SELECT * FROM prize WHERE id = {$winningPrizeId} for UPDATE");
                            Db::query("UPDATE prize SET winnum = winnum+1,residuenum = residuenum-1 WHERE id = {$winningPrizeId}");
                        }
                        break;
                    }
                }
            }
            
            $response = [
                'isWinner'          => ($winningPrize !== null),
                'winningPrizeId'    => $winningPrizeId,
                'winningPrize'      => $winningPrize,
            ];
            Db::commit();
            return $response;
        } catch (\Exception $e) {
            Db::rollback();
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }
    }

}